<template>
  <div class="list-orders">
    <!-- 返回按钮 -->
    <div class="back-button-container">
      <button class="back-button" @click="goBack">
        ← 返回
      </button>
    </div>

    <!-- 已支付订单信息 -->
    <h3>已支付订单信息</h3>
    <ul class="order">
      <li v-for="item in paidOrders" :key="item.id" class="order-item">
        <div class="order-info">
          <p>
            {{ item.business.businessName }}
            <i class="fa fa-caret-down" @click="toggleDetail(item)"></i>
          </p>
          <div class="order-info-right">
            <p>&#165;{{ item.orderTotal }}</p>
            <div class="order-actions" v-if="item.orderState === 1">
              <button class="action-button accept-button" @click="handleAction(item.id, 'accept')">去发货</button>
              <button class="action-button reject-button" @click="handleAction(item.id, 'cancel')">拒绝</button>
            </div>
          </div>
        </div>
        <ul class="order-detailed" v-show="item.isShowDetailet">
          <li v-for="odItem in item.orderItems" :key="odItem.id" class="detail-item">
            <p>{{ odItem.food.foodName }} x {{ odItem.quantity }}</p>
            <p>&#165;{{ (odItem.food.foodPrice * odItem.quantity).toFixed(2) }}</p>
          </li>
          <li class="detail-item">
            <p>配送费</p>
            <p>&#165;{{ item.deliveryAddress.deliveryPrice }}</p>
          </li>
          <li class="detail-item">
            <p><strong>下单时间:</strong> {{ formatDate(item.orderDate) }}</p>
            <p></p>
          </li>
        </ul>
      </li>
    </ul>

    <!-- 已发货订单信息 -->
    <h3>已发货订单信息</h3>
    <ul class="order">
      <li v-for="item in shipOrders" :key="'paid-' + item.id" class="order-item">
        <div class="order-info">
          <p>
            {{ item.business.businessName }}
            <i class="fa fa-caret-down" @click="toggleDetail(item)"></i>
          </p>
          <div class="order-info-right">
            <p>&#165;{{ item.orderTotal }}</p>
            <p><strong>状态: {{ getOrderStateText(item.orderState) }}</strong></p>
          </div>
        </div>
        <ul class="order-detailed" v-show="item.isShowDetailet">
          <li v-for="odItem in item.orderItems" :key="'paid-det-' + odItem.id" class="detail-item">
            <p>{{ odItem.food.foodName }} x {{ odItem.quantity }}</p>
            <p>&#165;{{ (odItem.food.foodPrice * odItem.quantity).toFixed(2) }}</p>
          </li>
          <li class="detail-item">
            <p>配送费</p>
            <p>&#165;{{ item.deliveryAddress.deliveryPrice }}</p>
          </li>
          <li class="detail-item">
            <p><strong>发货时间:</strong> {{ formatDate(item.orderDate) }}</p>
            <p><strong>订单号:</strong> {{ item.id }}</p>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router' // 引入 useRouter

// 使用 useRouter
const router = useRouter()

// 响应式数据
const loading = ref(false)
const error = ref('')
const user = reactive({})
const orderArr = ref([])

// 获取用户信息
const fetchUser = async () => {
  try {
    const token = sessionStorage.getItem('jwt')
    if(!token){
      this.$router.push({path:'/login'});
    }
    const response = await axios.get('/user', {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token.slice(1, -1)}` // 添加认证令牌
      }
    })
    user.value = response.data
    console.log('用户信息:', user.value)
  } catch (err) {
    console.error('获取用户信息失败:', err)
    error.value = '获取用户信息失败: ' + err.message
  }
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    error.value = ''

    // 确保已获取用户信息
    if (!user.value || !user.value.id) {
      await fetchUser()
      if (!user.value || !user.value.id) {
        throw new Error('无法获取用户ID')
      }
    }

    const userId = user.value.id
    console.log('获取用户ID:', userId, '的订单')

    const response = await axios.get('/orders/business/current', {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${sessionStorage.getItem('jwt')?.slice(1, -1)}`
      }
    })

    orderArr.value = response.data.data.map(order => ({
      ...order,
      isShowDetailet: false  // 初始化展开状态为收起
    }))

    console.log('订单数据:', orderArr.value)
  } catch (err) {
    console.error('获取订单失败:', err)
    error.value = '获取订单失败: ' + (err.response?.data?.message || err.message)
  } finally {
    loading.value = false
  }
}

// 切换订单详情显示/隐藏
const toggleDetail = (item) => {
  item.isShowDetailet = !item.isShowDetailet
}

// 获取订单状态文本
const getOrderStateText = (state) => {
  const stateMap = {
    1: '已支付',
    2: '已发货',
  }
  return stateMap[state] || '未知状态'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 计算属性：未支付订单
const shipOrders = computed(() => {
  return orderArr.value.filter(item => item.orderState === 2)
})

// 计算属性：已支付订单
const paidOrders = computed(() => {
  return orderArr.value.filter(item => item.orderState === 1)
})

// 返回按钮功能
const goBack = () => {
  router.go(-1)
}
// 通用订单操作：接单(accept) 或 拒绝(cancel)
const handleAction = async (orderId, action) => {
  try {
    const token = sessionStorage.getItem('jwt');
    if (!token) {
      alert('请先登录');
      router.push('/login');
      return;
    }

    const response = await axios.post(
        '/orders/business/action', // ✅ 使用新的后端接口
        null, // 通常 POST 表单参数用 params 或 body，这里使用 params
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token.slice(1, -1)}`
          },
          params: {  // ✅ action 和 orderId 通过 params 传参
            orderId: orderId,
            action: action
          }
        }
    );

    if (response.status === 200 || response.status === 201) { // 假设后端返回的 code 0 表示成功，根据你的 HttpResult 实际情况调整
      alert(response.data.message || '操作成功');
      await fetchOrders(); // 刷新订单列表
    } else {
      // 根据你的后端 HttpResult 结构，可能是 response.data.message
      const errorMsg = response.data?.message || '操作失败';
      alert('操作失败: ' + errorMsg);
    }
  } catch (err) {
    console.error('订单操作请求失败:', err);
    if (err.response && err.response.data) {
      alert('操作失败: ' + (err.response.data.message || '服务器错误'));
    } else {
      alert('网络异常，请检查连接');
    }
  }
};
// 组件挂载时执行
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.list-orders {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

/* 返回按钮样式 */
.back-button-container {
  margin-bottom: 20px;
}

.back-button {
  background-color: #0097FF;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #007BCC;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.error {
  background-color: #fee;
  color: #c33;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 20px;
  text-align: center;
}

h3 {
  color: #333;
  margin: 30px 0 15px 0;
  font-size: 18px;
  border-bottom: 2px solid #eee;
  padding-bottom: 5px;
}

.order {
  list-style: none;
  padding: 0;
  margin: 0;
}

.order-item {
  background: white;
  margin-bottom: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.order-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #fafafa;
  border-bottom: 1px solid #eee;
}

.order-info p {
  margin: 0;
  font-weight: 500;
  color: #333;
  display: flex;
  align-items: center;
  gap: 10px;
}

.order-info-right {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.order-info-right p {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #e74c3c;
}

.order-info-right-icon {
  background: #3498db;
  color: white;
  padding: 5px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.order-info-right-icon:hover {
  background: #2980b9;
}

.order-detailed {
  list-style: none;
  padding: 0;
  margin: 0;
  background: white;
}

.order-detailed .detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.order-detailed .detail-item:last-child {
  border-bottom: none;
}

.order-detailed .detail-item p {
  margin: 0;
  font-size: 14px;
  flex: 1;
}

.order-detailed .detail-item p:first-child {
  color: #666;
  font-weight: 500;
}

.order-detailed .detail-item p:last-child {
  color: #e74c3c;
  font-weight: bold;
  text-align: right;
  margin-left: 10px;
}

/* 美化展开图标 */
.fa-caret-down {
  cursor: pointer;
  color: #666;
  transition: transform 0.3s;
}

.fa-caret-down:hover {
  color: #333;
  transform: rotate(180deg);
}

/* 响应式设计 */
@media (max-width: 600px) {
  .list-orders {
    padding: 10px;
  }

  .order-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .order-info-right {
    align-self: flex-end;
    width: 100%;
    justify-content: flex-end;
  }

  .order-detailed .detail-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }

  .order-detailed .detail-item p:last-child {
    text-align: right;
    margin-left: 0;
  }
}
/* 操作按钮样式 */
.order-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.action-button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.accept-button {
  background-color: #28a745; /* 绿色，去发货/接单 */
  color: white;
}

.accept-button:hover {
  background-color: #218838;
}

.reject-button {
  background-color: #dc3545; /* 红色，拒绝/取消 */
  color: white;
}

.reject-button:hover {
  background-color: #c82333;
}
</style>